﻿#region namespaces

using System;
using System.Threading.Tasks;
using System.Xml.Linq;
using ZOIL.DataBackend.BaseX.XQueries;

#endregion

namespace ZOIL.DataBackend.BaseX
{
    public sealed partial class Database
    {
        public void Delete(long id)
        {
            if (!DeleteLocally(id))
            {
                throw new ArgumentException("Can't delete object with ID " + id + ": does not exist locally!", "id");
            }

            //aus db löschen:
            //als gelöscht in der db markieren und Event rumschicken
            var query = XQueriesLoader.GetDeleteObjectPairByIdQuery(id, DbConfig.DatabaseIdInIDatabaseObject, DbConfig.DatabaseIdInIVisualProperties);
            var evt = new XElement(EventType.Delete, new XAttribute("Id", id));
            var tQuery = Task.Factory.StartNew(() => _client.QuerySingle(query));
            var tEvent = Task.Factory.StartNew(() => SendEvent(evt));
            tQuery.Wait();
            tEvent.Wait();
        }

        private bool DeleteLocally(long id)
        {
            DatabaseObjectManager.DbItem dbi;
            return DeleteLocally(id, out dbi, true);
        }

        private bool DeleteLocally(long id, out DatabaseObjectManager.DbItem dbi, bool resetDatabaseId)
        {
            //muss lokal vorhanden sein zum entfernen
            if (!_localDbObjects.TryRemove(id, out dbi))
            {
                dbi = null;
                return false;
            }

            if (resetDatabaseId)
            {
                ResetDatabaseId(dbi);
            }

            //aufhören auf changes zu hören
            if (dbi.DatabaseObjectChangedListener != null)
            {
                try
                {
                    dbi.DatabaseObjectChangedListener.Dispose();
                    dbi.DatabaseObjectChangedListener = null;
                }
                catch (ObjectDisposedException)
                {
                }
            }
            if (dbi.VisualPropertiesChangedListener != null)
            {
                try
                {
                    dbi.VisualPropertiesChangedListener.Dispose();
                    dbi.VisualPropertiesChangedListener = null;
                }
                catch (ObjectDisposedException)
                {
                }
            }
            return true;
        }

        private void ResetDatabaseId(DatabaseObjectManager.DbItem dbi)
        {
//            dbi.DatabasePersistable.DatabaseId = default(long);
//            dbi.VisualProperties.BelongsToDatabaseId = default(long);
        }
    }
}